<?php
namespace Site\Model;

use Site\Model\Users;
use Zend\Db\TableGateway\TableGateway;
 
class UsersTable
{
    protected $tableGateway;
 
    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }
 
    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }
 
    public function getUsers($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }
 
    public function saveUsers(Users $User)
    {
         $data  = array('name' => $User->name,
                       'id'     => $User->id,
                       'last_name'  => $User->lastName,
                       'first_name'  => $User->firstName,
                       'pasport'    => $User->pasport,
                       'comments'    => $User->comments
                        );


        $id = (int)$User->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getUsers($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }
 
    public function deleteUser($id)
    {
        $this->tableGateway->delete(array('id' => $id));
    }
}